import type { ProColumns } from "@ant-design/pro-components";
import { EditableProTable, ActionType } from "@ant-design/pro-components";
import React, { useEffect, useState, useRef } from "react";
import { Button, Form, Modal } from "antd";
import { ExclamationCircleOutlined } from "@ant-design/icons";
import {
  getKeypadList,
  getByKeypadsId,
  saveKeypad,
  updateKeypad,
  removekeypad,
} from "@/api/keypad";

interface keypad {
  id: number;
  name: string;
  keyboard: string;
}

enum EditState {
  NONE,
  EDIT,
  CREATE,
}

const defaultData: keypad[] = [
  {
    id: 624748504,
    name: "前进",
    keyboard: "W",
  },
  {
    id: 624691229,
    name: "后退",
    keyboard: "Z",
  },
  {
    id: 624691230,
    name: "左转",
    keyboard: "A",
  },
  {
    id: 624691231,
    name: "右转",
    keyboard: "D",
  },
  {
    id: 624691232,
    name: "停止",
    keyboard: "S",
  },
];

export default function Keypad() {
  const [editableKeys, setEditableRowKeys] = useState<React.Key[]>([]);
  const [dataSource, setDataSource] = useState<keypad[]>(defaultData);
  const actionRef = useRef<ActionType>();
  const [form] = Form.useForm();
  const [editState, setEditState] = useState(EditState.NONE);
  const CREATE_DATA = "CREATE_DATA";

  const columns: ProColumns<keypad>[] = [
    {
      title: "名称",
      dataIndex: "name",
      width: "15%",
      editable: () => {
        return false;
      },
    },

    {
      title: "按键",
      dataIndex: "keyboard",
    },
    {
      title: "操作",
      valueType: "option",
      width: 200,
      render: (text, record, _, action) => [
        <a
          key="delete"
          onClick={() => {
            Modal.confirm({
              title: "您确定要删除此数据吗?",
              icon: <ExclamationCircleOutlined />,
              okText: "确认",
              cancelText: "取消",
              onOk: () => {
                removeAction(record.id as number);
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];

  const getListAction = () => {
    getKeypadList<keypad>().then(setDataSource);
  };

  const editAction = () => {
    setEditableRowKeys(dataSource.map((item) => item.id)); // dataSource
    setEditState(EditState.EDIT);
  };

  const saveAction = () => {
    if (editState === EditState.CREATE) {
      const list = dataSource.filter((item) => item.id === CREATE_DATA);
      saveKeypad(list).then(() => {
        setEditableRowKeys([]);
        setEditState(EditState.NONE);
        getListAction();
      });
    } else {
      updateKeypad(dataSource).then(() => {
        setEditableRowKeys([]);
        setEditState(EditState.NONE);
        getListAction();
      });
    }
  };

  const removeAction = (id: number) => {
    removekeypad(id).then(() => {
      const result = dataSource.filter((item) => item.id !== id);
      setDataSource(result);
    });
  };

  useEffect(() => {
    getListAction();
  }, []);

  return (
    <div className="size-full flex flex-col">
      <div className="flex flex-row justify-end gap-2 p-4">
        <Button type="primary" onClick={editAction}>
          编辑
        </Button>
        <Button type="primary" onClick={saveAction}>
          保存
        </Button>
        <Button
          type="primary"
          onClick={() => {
            form.resetFields();
            actionRef.current?.addEditRecord?.({
              id: `CREATE_DATA_${Date.now()}`,
              name: "",
              keyboard: "",
            });
          }}
        >
          添加功能
        </Button>
      </div>
      <div className="flex-1">
        <EditableProTable<keypad>
          className="size-full"
          size="middle"
          rowKey="id"
          actionRef={actionRef}
          recordCreatorProps={false}
          columns={columns}
          value={dataSource}
          editable={{
            form,
            type: "multiple",
            editableKeys,
            onChange: (editableKeys: React.Key[]) => {
              console.log("editableKeys", editableKeys);
              setEditableRowKeys(editableKeys);
            },
            onValuesChange: (record, recordList) => {
              const data = recordList.map((item) => (item.id ? item : record));
              setDataSource(data);
            },
          }}
        />
      </div>
    </div>
  );
}
